//package com.hydra.gateway.listener;
//
//import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
//import com.alibaba.nacos.api.NacosFactory;
//import com.alibaba.nacos.api.annotation.NacosInjected;
//import com.alibaba.nacos.api.config.ConfigService;
//import com.alibaba.nacos.api.config.listener.Listener;
//import com.alibaba.nacos.api.exception.NacosException;
//import com.alibaba.nacos.api.naming.NamingService;
//import com.hydra.base.utils.JsonUtil;
//import lombok.extern.log4j.Log4j2;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.cloud.gateway.config.GatewayProperties;
//import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
//import org.springframework.cloud.gateway.route.RouteDefinition;
//import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
//import org.springframework.context.ApplicationEventPublisher;
//import org.springframework.context.ApplicationEventPublisherAware;
//import org.springframework.stereotype.Component;
//import reactor.core.publisher.Mono;
//
//import javax.annotation.PostConstruct;
//import javax.annotation.Resource;
//import java.util.ArrayList;
//import java.util.List;
//import java.util.Properties;
//import java.util.concurrent.Executor;
//
//@Component
//@Log4j2
//public class NacosDynamicRouteService implements ApplicationEventPublisherAware {
//    private static final String dataId = "gateway-routes";
//
//    @Value("${spring.cloud.nacos.config.group}")
//    private String group;
//
//    @Resource
//    private RouteDefinitionWriter routeDefinitionWriter;
//
//    private ApplicationEventPublisher applicationEventPublisher;
//
//    private static final List<String> ROUTE_LIST = new ArrayList<>();
//
//    // Nacos注册中心配置信息 包括我们需要的NamingService也能在里面获取到
//    @Resource
//    private NacosDiscoveryProperties nacosDiscoveryProperties;
//
//    // Gateway的路由信息配置会被提前加载好我们直接注入即可，一般我们会把路由id设置成各个服务名称，这里需要服务名称直接读取路由id
//    @Resource
//    private GatewayProperties gatewayProperties;
//
//    @PostConstruct
//    public void dynamicRouteByNacosListener() {
//        try {
//            //获取 NamingService
//            NamingService namingService = nacosDiscoveryProperties.namingServiceInstance();
//            //获取所有的服务名称 这里从gateway路由信息中获取
//            List<RouteDefinition> routes = gatewayProperties.getRoutes();
//            //订阅服务，服务状态刷新时，更新ribbon
//            routes.forEach(item -> {
//                String service = item.getId();
//                //订阅服务状态发生改变时，刷新 ribbon 服务实例
//                try {
//                    namingService.subscribe(service,(event -> {
//                        log.info("收到订阅 nacos 服务");
//                        log.info("刷新服务实例：{}",service);
//
//                        log.info("刷新服务实例成功：{}",service);
//                    }));
//                } catch (NacosException e) {
//                    log.error("订阅 nacos 服务失败,error:{}",e.getErrMsg());
//                    e.printStackTrace();
//                }
//            });
//
//
//            ConfigService configService = NacosFactory.createConfigService(nacosDiscoveryProperties.getNacosProperties());
//            configService.getConfig(dataId, group, 5000);
//            configService.addListener(
//                    dataId,
//                    group,
//                    new Listener() {
//                        @Override
//                        public void receiveConfigInfo(String configInfo) {
//                            clearRoute();
//                            try {
//                                List<RouteDefinition> gatewayRouteDefinitions = JsonUtil.parseArray(configInfo, RouteDefinition.class);
//                                log.warn("更新路由:{}", gatewayRouteDefinitions);
//                                for (RouteDefinition routeDefinition : gatewayRouteDefinitions) {
//                                    addRoute(routeDefinition);
//                                }
//                                publish();
//                            } catch (Exception e) {
//                                log.error("更新路由出现异常", e);
//                            }
//                        }
//
//                        @Override
//                        public Executor getExecutor() {
//                            return null;
//                        }
//                    });
//        } catch (NacosException e) {
//            log.error("nacos监听路由出现异常", e);
//        }
//    }
//
//    private void clearRoute() {
//        for (String id : ROUTE_LIST) {
//            this.routeDefinitionWriter.delete(Mono.just(id)).subscribe();
//        }
//        ROUTE_LIST.clear();
//    }
//
//    private void addRoute(RouteDefinition definition) {
//        try {
//            routeDefinitionWriter.save(Mono.just(definition)).subscribe();
//            ROUTE_LIST.add(definition.getId());
//        } catch (Exception e) {
//            log.error("增加路由出现异常", e);
//        }
//    }
//
//    private void publish() {
//        this.applicationEventPublisher.publishEvent(new RefreshRoutesEvent(this.routeDefinitionWriter));
//    }
//
//    @Override
//    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
//        this.applicationEventPublisher = applicationEventPublisher;
//    }
//}
